package com.xuebusi.nio.client;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

/**
 * 客户端线程类, 专门接收服务器端响应信息
 */
public class NioClientHandler implements Runnable {

    private Selector selector;

    public NioClientHandler(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {
        try {
            /**
             * 循环等待新接入的连接
             */
            for (; ; ) {
                // 获取可用的channel数量
                int readyChannels = selector.select();
                if (readyChannels == 0) continue;
                // 获取所有已经就绪(可用)的channel集合
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> it = keys.iterator();
                while (it.hasNext()) {
                    SelectionKey selectionKey = it.next();
                    // 移除集合中当前key
                    it.remove();

                    /**
                     * 7.根据就绪状态，调用对应的方法处理业务逻辑
                     */
                    // 如果是可读事件
                    if (selectionKey.isReadable()) {
                        readHandler(selectionKey, selector);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 可读事件处理器
     *
     * @param selectionKey
     * @param selector
     * @throws IOException
     */
    private void readHandler(SelectionKey selectionKey, Selector selector) throws IOException {
        // 从selectionKey中获取到已经就绪的channel
        SocketChannel sc = (SocketChannel) selectionKey.channel();

        // 创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        // 循环读取服务器端响应信息
        String response = "";
        while (sc.read(byteBuffer) > 0) {
            // 切换为读模式
            byteBuffer.flip();
            // 读取buffer中的内容
            response += Charset.forName("UTF-8").decode(byteBuffer);
        }
        // 将channel再次注册到selector上,监听他的可读事件
        sc.register(selector, SelectionKey.OP_READ);

        // 将服务器端响应信息打印到本地
        if (response.length() > 0) {
            System.out.println(response);
        }
    }
}
